;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Merchant.Scepter", [])
        .controller("MerchantScepterCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService) {
            var tabMap = {
                0:'新增',
                1:'编辑'
            };
            $scope.tabFlag= {
                name: '',
                type: 0
            };
            $scope.markInfo = {
                allChecked:false
            };
            $scope.menuList = [];
            $scope.condition = {};
            $scope.activeFlag = [true,false,false];
            $scope.detailInfo = {};
            $scope.submitted = false;
            $scope.currentScepter = {};
            $scope.authCode = {};
            $scope.authCodeSelected = [];
            var menuTypeList = [];

            var btnPermissionCode = {
                templateAdd: window.ActionCode.templateAdd,
                templateDel: window.ActionCode.templateDel,
                templateEdit: window.ActionCode.templateEdit,
                templateConfig: window.ActionCode.templateConfig
            };

            $scope.btnPermission = {
                templateAdd: true,
                templateDel: true,
                templateEdit: true,
                templateConfig: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function initData() {
                setMenuInit($scope.menuList);
                $scope.detailInfo = {};
                $scope.submitted = false;
                $scope.tabFlag= {
                    name: '',
                    type: 0
                };
            }

            function setMenuInit(list) {
                angular.forEach(list,function (item) {
                    item.isChecked = false;
                    if(!!item.children){
                        setMenuInit(item.children)
                    }
                })
            }
            function getScepterList() {
                var service = "auth";
                var reqUrl = "/template/list";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value;
                    angular.forEach($scope.dataList,function (item) {
                        item.isChecked = false;
                    })
                });
            }
            function getTempDetail(id) {
                $scope.authCode = {};

                var service = "auth";
                var reqUrl = "/template/queryTemplateConfig";
                var param = {};
                param.tempId = id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.authCodeSelected = resp.value.authIds;

                    for (var i = 0; i < resp.value.authIds.length; i++) {
                        $scope.authCode[resp.value.authIds[i]] = true;
                    }
                    setNodeStatus($scope.menuList, resp.value.menuIds);
                })
            }
            function getAllMenu(site) {
                var service = 'auth';
                var reqUrl = '/menu/listMenuBySite';
                ybHttp.Get(service, reqUrl,{site:site}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    menuTypeList[site] = resp.value;
                });
            }
            function setNodeStatus(menuList, authCode) {
                var menuList = {
                    children: menuList
                };
                angular.forEach(authCode, function (authItem) {
                    function setMenu(menuList) {
                        angular.forEach(menuList.children, function (item) {
                            if (authItem === item.id) {
                                item.isChecked = true;
                                return false;
                            }
                            if ((item.leaf === 0) && item.children.length > 0) {
                                setMenu(item);
                            }
                        });
                    }

                    setMenu(menuList);
                });
                checkTreeState();
            }

            function checkTreeState() {
                var menuList = {
                    children: $scope.menuList
                };

                function setTreeState(menuList) {
                    angular.forEach(menuList.children, function (item) {
                        if ((item.leaf === 0) && item.children.length > 0) {
                            setTreeState(item);
                            item.isChecked = checkNodeState(item.children);
                        }
                    });
                }
                setTreeState(menuList);
            }
            function checkNodeState(menu) {
                var selectAll = false;
                var selectedCount = 0;
                var selectedHalf = 0;
                for (var i = 0, len = menu.length; i < len; i++) {
                    if (menu[i].isChecked === true) {
                        selectedCount++;
                    }
                    if (menu[i].isChecked === "notAll") {
                        selectedHalf++;
                    }
                }
                if (selectedCount === 0 && selectedHalf === 0) {
                    selectAll = false;
                } else if (selectedCount === menu.length) {
                    selectAll = true;
                } else {
                    selectAll = "notAll";
                }
                return selectAll;
            }

            function changeSubState(node) {
                var checked = node.isChecked;
                if ((node.leaf === 0) && node.children.length > 0) {
                    angular.forEach(node.children, function (item) {
                        item.isChecked = checked;
                        changeSubState(item);
                    })
                }
            }

            // 获取父节点
            function findParentNode(parentId) {
                var parentItem = [];
                var menuList = {
                    children: $scope.menuList
                };
                function findNode(list) {
                    angular.forEach(list.children, function (item) {
                        if (item.id === parentId) {
                            parentItem = item;
                        } else {
                            if ((item.leaf === 0) && item.children.length > 0) {
                                findNode(item);
                            }
                        }
                    });
                }
                findNode(menuList);
                return parentItem;
            }

            function changeParentState(parentId) {
                var parentItem = findParentNode(parentId);
                if ((parentItem.leaf === 0) && parentItem.children.length > 0) {
                    parentItem.isChecked = checkNodeState(parentItem.children);
                }
                if (parentItem.parentId !== 0) {
                    changeParentState(parentItem.parentId)
                }
            }
            function getCheckedItems() {
                var selectedItems = [];
                function findCheckedItem(list) {
                    angular.forEach(list, function (item) {
                        if (!!item.isChecked) {
                            selectedItems.push(item.id);
                        }
                        if ((item.leaf === 0) && (item.children.length > 0)) {
                            findCheckedItem(item.children);
                        }
                    })
                }
                findCheckedItem($scope.menuList);
                return selectedItems;
            }

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }
            function delFunc(ids) {
                var service = "auth";
                var reqUrl = "/template/remove";
                ybHttp.Post(service, reqUrl, ids).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getScepterList();
                })
            }
            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
            };

            // 改变被点击节点状态
            $scope.changeState = function (node, notSetMenu) {
                // 设置子节点状态
                changeSubState(node);
                // 当此节点不是最高级时，改变父节点状态
                if (node.parentId !== 0) {
                    changeParentState(node.parentId);
                }
                !notSetMenu && setMenuAuth(node);
            };

            // 设置菜单下的所有权限状态
            function setMenuAuth (item) {
                var isChecked = item.isChecked;
                angular.forEach(item.auths, function (auth) {
                    var authId = auth.authId;
                    var index = $scope.authCodeSelected.indexOf(authId);
                    if (isChecked && index < 0) {
                        $scope.authCodeSelected.push(authId);
                        $scope.authCode[authId] = true;
                    }
                    if (!isChecked && index >= 0) {
                        $scope.authCodeSelected.splice(index, 1);
                        $scope.authCode[authId] = false;
                    }
                });
                if (item.children && item.children.length > 0) {
                    angular.forEach(item.children, function (child) {
                        setMenuAuth(child)
                    });
                }
            }

            $scope.selectAuth = function (authId, thdItem) {
                if ($scope.authCodeSelected.indexOf(authId) > -1) {
                    $scope.authCodeSelected.splice($scope.authCodeSelected.indexOf(authId), 1);
                } else {
                    $scope.authCodeSelected.push(authId);
                }
                
            };

            $scope.search = function () {
                getScepterList();
            };
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false,false,false];
                $scope.activeFlag[index] = true;
                switch (index){
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };
            $scope.goSetTemp = function (item) {
                $scope.menuList = menuTypeList[item.site];
                getTempDetail(item.id);
                $scope.changeTab(2);
            };
            $scope.getScepter = function (item) {
                if($scope.currentScepter.id == item.id){
                    return;
                }
                $scope.currentScepter = item;
            };
            $scope.goAdd = function () {
                $scope.changeTab(1);
                $scope.tabFlag.name = tabMap[0];
                $scope.tabFlag.type = 0;
            };

            $scope.goEdit = function (item) {
                $scope.detailInfo = item;
                $scope.changeTab(1);
                $scope.tabFlag.name = tabMap[1];
                $scope.tabFlag.type = 1;
            };

            $scope.batchDel = function () {
                var ids = [];
                angular.forEach($scope.dataList,function (item) {
                    if(item.isChecked){
                        ids.push(item.id);
                    }
                });
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    delFunc(ids);
                })
            };

            $scope.delData = function (index) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var ids = [];
                    ids.push($scope.dataList[index].id);
                    delFunc(ids);
                })
            };
            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "auth";
                var reqUrl = "/template/insert";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/template/update";
                }
                // $scope.detailInfo.site = 2;
                ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getScepterList();
                    $scope.changeTab(0);
                });
            };
            $scope.saveTemplate = function () {
                var service = "auth";
                var reqUrl = "/template/configTemplate";
                var param = {};
                param.tempId = $scope.currentScepter.id;
                param.menuIds = getCheckedItems();
                param.authIds = $scope.authCodeSelected;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            // 评级管理菜单下的操作权限，因权限层次过多，单独拎出来不走接口手动分层
            $scope.ratingAuthList = [
                {
                    name: '评级管理',
                    auths: [
                        { name: '新增', authId: 1200001 }, { name: '编辑', authId: 1200002 }, { name: '删除', authId: 1200003 },
                        { name: '制定规则', authId: 1200004 }, { name: '生成评分', authId: 1200005 }, { name: '查看评分', authId: 1200006 },
                        { name: '评级制定', authId: 1200007 }
                    ]
                },
                {
                    name: '销售完成情况配置',
                    auths: [
                        { name: '新增', authId: 1200008 }, { name: '编辑', authId: 1200009 }, { name: '删除', authId: 1200010 },
                        { name: '配置时间', authId: 1200011 }, { name: '导入', authId: 1200012 }
                    ]
                },
                {
                    name: '月度计划准确性配置',
                    auths: [
                        { name: '提交', authId: 1200013 }
                    ]
                },
                {
                    name: '订单管理规范配置',
                    auths: [
                        { name: '提交', authId: 1200014 }
                    ]
                },
                {
                    name: '应收逾期配置',
                    auths: [
                        { name: '编辑', authId: 1200015 }, { name: '删除', authId: 1200016 }, { name: '导入', authId: 1200017 }
                    ]
                },
                {
                    name: '总体销售完成率配置',
                    auths: [
                        { name: '新增', authId: 1200018 }, { name: '编辑', authId: 1200019 }, { name: '删除', authId: 1200020 },
                        { name: '配置时间', authId: 1200021 }, { name: '导入', authId: 1200022 }
                    ]
                },
                {
                    name: '库存管理及业务规范性加减分',
                    auths: [
                        { name: '新增', authId: 1200023 }, { name: '编辑', authId: 1200024 }, { name: '删除', authId: 1200025 },
                        { name: '导入', authId: 1200026 }
                    ]
                },
                {
                    name: '查看评分',
                    auths: [
                        { name: '生成排名', authId: 1200027 }, { name: '导出', authId: 1200028 }, { name: '销售完成情况-编辑', authId: 1200030 },
                        { name: '月度计划准确性-编辑', authId: 1200031 }, { name: '订单管理规范性-编辑', authId: 1200032 }, { name: '应收账款逾期-编辑', authId: 1200033 },
                        { name: '总体销售完成率-编辑', authId: 1200034 }, { name: '规范性管理加减分-编辑', authId: 1200035 },
                    ]
                },
                {
                    name: '评级制定',
                    auths: [
                        { name: '保存', authId: 1200029 },
                    ]
                },
            ];

            (function () {
                getScepterList();
                getAllMenu(1);
                getAllMenu(2);
                setBtnPermission();
            })()
        }])
    ;
})(window, window.angular);